package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.product.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Service
public class TestServiceImpl implements TestService {

    private final Lock lock = new ReentrantLock();

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void lock() {
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", "111");
        if (lock){
            //lock: true  表示未上锁
            Integer num = (Integer) redisTemplate.opsForValue().get("num");
            num++;
            redisTemplate.opsForValue().set("num",num);

            //删除lock 表示解锁

        }else {
            //lock: false  表示未上锁
            lock();
        }
    }


  /*  @Override
    public void lock() {

        lock.lock();
        try {
            Integer num = (Integer) redisTemplate.opsForValue().get("num");
            num++;
            redisTemplate.opsForValue().set("num",num);
        } finally {
            lock.unlock();
        }

    }*/
}
